package com.travel.server.manager.impl.command.project.data;

import com.travel.common.util.DateUtil;
import com.travel.server.manager.dto.request.project.data.UpdateProjectConsulRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.ProjectDal;
import com.travel.server.manager.impl.dal.data.ConsultDal;
import com.travel.server.manager.impl.dal.data.ConsultDal.ConsultParam;
import com.travel.server.manager.model.ProjectConsult;
import com.travel.server.manager.model.ProjectInfo;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/29 12:08
 * @Desc:
 */
@Component
@Slf4j
public class UpdateProjectConsulCommand extends AbstractCommand<UpdateProjectConsulRequest, EmptyResponse> {

    @Autowired
    private ConsultDal consultDal;

    @Autowired
    private ProjectDal projectDal;

    @Override
    protected void checkInput(UpdateProjectConsulRequest request) {
        if(request.getId() == null || StringUtils.isBlank(request.getDataDate())){
            throwInvalidParam();
        }
    }

    @Override
    public EmptyResponse handle(UpdateProjectConsulRequest request) {
        checkInput(request);

        UserInfo userInfo = getUserInfo();
        Date now = new Date();

        ProjectInfo projectInfo = projectDal.selectById(request.getId());

        Date dataDate = DateUtil.getDataTime(request.getDataDate());

        ConsultParam param = new ConsultParam();

        param.setProjectId(request.getId());
        param.setDataDate(dataDate);

        ProjectConsult projectConsult = consultDal.selectProjectConsult(param);
        if(projectConsult == null){
            projectConsult = new ProjectConsult();
            projectConsult.setCreateBy(userInfo.getName());
            projectConsult.setCreateTime(now);
        }
        projectConsult.setConsult(request.getConsul());
        projectConsult.setDataDate(dataDate);
        projectConsult.setProjectId(projectInfo.getId());
        projectConsult.setUpdateBy(userInfo.getName());
        projectConsult.setUpdateTime(now);

        consultDal.insertOrUpdate(projectConsult);
        return new EmptyResponse();
    }
}
